package com.qf.java2201.edu.userservice.web.service;

import com.qf.java2201.edu.userservice.dto.Token;
import com.qf.java2201.edu.userservice.token.TokenService;
import com.qf.java2201.edu.userservice.web.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * @date 2022/6/5
 * @desc
 */
@Component
public class LoginService {


    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;


    /**
     * 走security 的登录流程 返回 token
     * */
    public String login(String userName, String password) {
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName, password));
        } catch (Exception e) {
            e.printStackTrace();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();


        //return tokenService.generateToken(loginUser.getUserId(), loginUser.getUsername());
        // 把认证成功的用户信息存入 redis
        Token token = tokenService.saveToken(loginUser);
        return token.getToken();
    }




}
